import {
  Card,
  message,
  Modal,
  Table,
  Button,
  Form,
  Input,
  UploadProps,
} from "antd";
import {
  DeleteOutlined,
  EditOutlined,
  LoadingOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/lib/table";
import { useEffect, useState } from "react";
import trademarkApi, { TrademarkData } from "@/api/user/pintai";
import Upload, { RcFile, UploadChangeParam, UploadFile } from "antd/lib/upload";
import { t } from "i18next";
export default function ArrtList() {
  const [trademarkList, setTrademarkList] = useState<any>();
 
   //分页
   let [loading,setLoading]=useState()
   let [total, setTotal] = useState<number>(0);
   let [current, setCurrent] = useState<number>(1);
   let [pageSize, setPageSize] = useState<number>(3);
 
   const getInfoList = async (page: number, limit: number) => {
     const result = await trademarkApi.getPageListInfo(page, limit);
     setTrademarkList(result.records);
     setTotal(result.total);
     setCurrent(result.current);
     setPageSize(result.size);
     console.log(result);
   };
 
   useEffect(() => {
     getInfoList(current, pageSize);
   }, [current, pageSize]);
 
  // 删除
  const deleteTrademark = async (row: TrademarkData) => {
    await trademarkApi.remove(row.id as number);
    getInfoList(current, pageSize);
  };
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      align: "center",
      width: 80,
      dataIndex: "id",
      render: (x: any, y: any, index: number) => {
        return index + 1;
      },
    },
    {
      title: "品牌名称",
      width: 200,
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      width: 200,
      dataIndex: "logoUrl",
      render: (row) => <img className="hospital-logo" src={row} />,
    },
    {
      title: "操作",
      width: 200,
      render: (row) => {
        // console.log('render', value, row, index)
        return (
          <>
            <Button
              type="primary"
              className="ziti"
              size="small"
              icon={<EditOutlined />}
            >
              修改
            </Button>
            <Button
              type="primary"
              className="font ml"
              danger
              size="small"
              onClick={() => deleteTrademark(row)}
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];
  //对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  //收集数据
  // var [tmFrom] = useState<TrademarkData>();
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  //表单
  const [form] = Form.useForm();
  const onFinish = async (values: any) => {
    let tmFrom = {
      tmName: values.tmName,
      logoUrl: (values.logoUrl[0] || []).response.data,
    };
    // setTmFrom(tmFrom)
    await trademarkApi.addOrUpdate(tmFrom);
    getInfoList(current, pageSize);
    console.log("数据表单111-->", values);
  };
  const handleOk = async () => {
    // onFinish(tmFrom)
    form
      .validateFields()
      .then((values) => {
        onFinish(values);
        setImageUrl(values.logoUrl);
        setIsModalOpen(false);
      })
      .catch((errorInfo) => {
        message.error(errorInfo);
      });
  };

  const normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  const getValueFromEvent = { normFile };
  console.log(getValueFromEvent);
  
  //上传图片
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const [imageUrl, setImageUrl] = useState<string>();

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      // setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      getBase64(info.file.originFileObj as RcFile, (url) => {
        // setLoading(false);
        setImageUrl(url);
      });
    }
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 22 }}></div>
    </div>
  );

  return (
    <Card>
      <div className="mtb">
        <Button type="primary" onClick={showModal} icon={<PlusOutlined />}>
          添加
        </Button>
      </div>
      {/* //弹出对话框 */}
      <Modal
        title="添加品牌"
        style={{ top: 0 }}
        visible={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {/* 表单 */}
        <Form
          name="tmName"
          form={form}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 22 }}
          onFinish={onFinish}
        >
          {/* {" "} */}
          <Form.Item
            label="品牌名称"
            name="tmName"
            // rules={[{ required: true, message: "Please input your username!" }]}
          >
            <Input />
          </Form.Item>
        </Form>

        {/* 上传图片 */}
        <Upload
          listType="picture-card"
          className="avatar-uploader"
          showUploadList={false}
          action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
          beforeUpload={beforeUpload}
          onChange={handleChange}
        >
          {imageUrl ? (
            <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
          ) : (
            uploadButton
          )}
        </Upload>
      </Modal>
      <Table
        columns={columns}
        dataSource={trademarkList}
        bordered
        rowKey="id"
        pagination={{
          total: total,
          pageSize: pageSize,
          current: current,
          showSizeChanger: true, //是否显示修改每页数量的下拉框
          pageSizeOptions: [3, 5, 7, 10], //指定可选每页数量的数组
          showQuickJumper: true, //是否显示快速跳转页码的输入框
          showTotal:(total) => `${t("total")}${total}`,
          onChange: (page, limit) => {
            // 发送请求，请求新的数据
            getInfoList(page, limit);
          },
        }}
      />
    </Card>
  );
}
